<template>
	<div :class="{ fullscreen: fullscreen }" class="tinymce-container" :style="{ width: containerWidth }">
		<textarea :id="tinymceId" class="tinymce-textarea" @paste="pasteChange" />
		<!-- <textarea style="heigth: 1=300px;width: 100px;background-color: red;" ></textarea> -->
		<div class="editor-custom-btn-container">
			<editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
		</div>
	</div>
</template>

<script>
import editorImage from './components/EditorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'
import menuJson from './menu.json'

import ala from 'ala'
const tinymceCDN = 'https://ui.5ug.com/tinymce.min.js'

export default {
	name: 'Tinymce',
	components: {
		editorImage
	},
	model: {
		prop: 'dataModel',
		event: 'change'
	},
	props: {
		dataModel: {},
		value: {
			type: String,
			default: ''
		},
		toolbar: {
			type: Array,
			required: false,
			default () {
				return []
			},
			textType: {
				default: null
			}
		},
		menubar: {
			type: String,
			default: 'edit insert view format table'
		},
		height: {
			type: [Number, String],
			required: false,
			default: 360
		},
		width: {
			type: [Number, String],
			required: false,
			default: 'auto'
		}
	},
	data () {
		return {
			hasChange: false,
			hasInit: false,
			tinymceId: 'vue-admin-tinymceId',
			fullscreen: false,
			languageTypeList: {
				'en': 'en',
				'zh': 'zh_CN',
				'es': 'es_MX',
				'ja': 'ja'
			}
		}
	},
	computed: {
		containerWidth () {
			const width = this.width
			if (/^[\d]+(\.[\d]+)?$/.test(width)) {
				return `${width}px`
			}
			return width
		}
	},
	watch: {
		value (val) {
			if (!this.hasChange && this.hasInit) {
				this.$nextTick(() =>
					window.tinymce.get(this.tinymceId).setContent(val || ''))
			}
		}
	},
	mounted () {
		this.init()
	},
	activated () {
		if (window.tinymce) {
			this.initTinymce()
		}
	},
	deactivated () {
		this.destroyTinymce()
	},
	destroyed () {
		this.destroyTinymce()
	},
	methods: {
		pasteChange (ev) { },
		init () {
			this.tinymceId += '_' + Date.now()
			load(tinymceCDN, (err) => {
				if (err) {
					this.$message.error(err.message)
					return
				}
				this.initTinymce()
			})
		},
		initTinymce () {
			const _this = this
			window.tinymce.init({
				selector: `#${this.tinymceId}`,
				language: this.languageTypeList['zh'],
				height: this.height,
				body_class: 'vue-admin-panel-body ',
				object_resizing: false,
				toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
				plugins: plugins,
				menubar: '', // 是否启用菜单栏
				menu: {
					'edit': menuJson.edit,
					'insert': menuJson.insert,
					'view': menuJson.view,
					'format': menuJson.format,
					'table': menuJson.table
				}, // 菜单配置
				end_container_on_empty_block: true,
				powerpaste_word_import: 'clean',
				code_dialog_height: 450,
				code_dialog_width: 1000,
				advlist_bullet_styles: 'square',
				advlist_number_styles: 'default',
				default_link_target: '_blank',
				link_title: false,
				nonbreaking_force_tab: true,
				paste_data_images: true,
				init_instance_callback: editor => {
					if (_this.value) {
						editor.setContent(_this.value)
					}
					_this.hasInit = true
					editor.on('NodeChange Change KeyUp SetContent', () => {
						this.hasChange = true
						this.$emit('change', editor.getContent())
					})
				},
				images_upload_handler: async (blobInfo, success, failure) => {
					var form = new FormData()
					form.append('files', blobInfo.blob(), blobInfo.filename())
					var repones = await _this.$ala.httpPost('Api/StorageFile/upload', form)
					success(_this.$ala.urlImage(repones.path))
				},
				setup (editor) {
					editor.on('FullscreenStateChanged', (e) => {
						_this.fullscreen = e.state
					})
				}
			}).then(res => {
				this.setContent(this.dataModel)
			})
		},
		destroyTinymce () {
			const tinymce = window.tinymce.get(this.tinymceId)
			if (this.fullscreen) {
				tinymce.execCommand('mceFullScreen')
			}

			if (tinymce) {
				tinymce.destroy()
			}
		},
		setContent (value) {
			if (window.tinymce.get(this.tinymceId)) {
				window.tinymce.get(this.tinymceId).setContent(value)
			} else {
				this.initTinymce()
			}
		},
		getContent () {
			window.tinymce.get(this.tinymceId).getContent()
		},
		imageSuccessCBK (arr) {
			const _this = this
			arr.forEach(v => {
				window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v}" >`)
			})
		}
	}
}
</script>

<style scoped>
.tinymce-container {
	position: relative;
	line-height: normal;
}

.tinymce-container>>>.mce-panel {
	border: 0 solid #f3f3f3;
}

.tinymce-container>>>.mce-fullscreen {
	z-index: 10000;
}

.tinymce-textarea {
	visibility: hidden;
	z-index: -1;
}

.editor-custom-btn-container {
	position: absolute;
	right: 4px;
	top: 4px;
}

.fullscreen .editor-custom-btn-container {
	z-index: 10000;
	position: fixed;
}

.editor-upload-btn {
	display: inline-block;
}
</style>